﻿using SuperX.Common;
using SuperX.Common.BasicService;
using SuperX.Common.Log;
using SuperX.Common.Object;
using SqlSugar;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace SuperX.DataCenterService.MomAPI.Model
{
    public class ScreenDesginController : BasicObject, MomApi
    {
        private IProject _project = BasicServiceManager.GetProjService().Project;
        private SqlSugarClient _db;

        private readonly DataCenterServer _server;

        public ScreenDesginController(DataCenterServer server)
        {
            Name = nameof(ScreenDesginController);
            _server = server;
            ProcessedInit();
        }

        /// <summary>
        /// 初始化db
        /// </summary>
        public void ProcessedInit()
        {
            // 创建SqlSugar实例
            _db = CreateClient();
            _db.CodeFirst.InitTables(typeof(ScreenDesginRecord));
        }

        private SqlSugarClient CreateClient(string dbName = "ScreenDesgin")
        {
            var runtime = Path.Combine(_project.ProjectDir, "Runtime");
            if (!Directory.Exists(runtime)) Directory.CreateDirectory(runtime);
            var path = Path.Combine(_project.ProjectDir, "Runtime", $"{dbName}.db");
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = $"Data Source={path};",
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            });
            return Db;
        }

        #region 接口方法

        /// <summary>
        /// 获取所有模板列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response search(searchReq req)
        {
            Response res = new Response();
            var search = new SearchResult();
            try
            {
                List<ScreenDesginRecord> listScreenDesgin;
                if (req.offset < 0 && req.limit < 0)
                {
                    listScreenDesgin = _db.Queryable<ScreenDesginRecord>().OrderBy(x => x.id).ToPageList(req.offset, req.limit).ToList();
                }
                else
                {
                    listScreenDesgin = _db.Queryable<ScreenDesginRecord>().OrderBy(x => x.id).ToList();
                }
                List<DataItem> listDataItem = new List<DataItem>();
                foreach (var screenDesgin in listScreenDesgin)
                {
                    DataItem dataItem = new DataItem();
                    dataItem.id = screenDesgin.id;
                    dataItem.title = screenDesgin.title;
                    dataItem.content = screenDesgin.content;
                    dataItem.image_url = JsonConvert.DeserializeObject<List<Image_urlItem>>(screenDesgin.image_url);
                    dataItem.state = screenDesgin.state;
                    dataItem.update_date = screenDesgin.update_date;
                    listDataItem.Add(dataItem);
                }
                search.values = listDataItem;
                res.result = new Result { data = search };
            }
            catch (Exception ex)
            {
                Logger.Warn($"获取所有模板列表出现异常!{ex}");
                res.result = null;
            }
            return res;
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public Response delete(deleteReq req)
        {
            Response res = new Response();
            try
            {
                if (req.ids.Count > 0)
                {
                    _db.Deleteable<ScreenDesginRecord>().In(a => a.id, req.ids).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                Logger.Warn($"删除模板出现异常!{ex}");
                res.result = new Result() { data = false };
            }
            res.result = new Result() { data = true };
            return res;
        }

        /// <summary>
        /// 发布/取消发布模板
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response onlineOrOffline(onlineofflineReq req)
        {
            Response res = new Response();
            try
            {
                if (req.ids.Count >= 0 && !String.IsNullOrEmpty(req.state))
                {
                    var listScreenDesgin = _db.Queryable<ScreenDesginRecord>().In(a => a.id, req.ids).ToList();
                    foreach (var screenDesgin in listScreenDesgin)
                    {
                        screenDesgin.state = req.state;
                        screenDesgin.update_date = System.DateTime.Now.ToString();
                    }
                    _db.Updateable(listScreenDesgin).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                Logger.Warn($"发布/取消发布模板出现异常!{ex}");
                res.result = null;
            }
            return res;
        }

        /// <summary>bh
        /// 暂存，保存画布
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response update(updateReq req)
        {
            Response res = new Response();
            try
            {
                if (req.ids.Count > 0 && req.values != null)
                {
                    var listScreenDesgin = _db.Queryable<ScreenDesginRecord>().In(a => a.id, req.ids).ToList();
                    foreach (var screenDesgin in listScreenDesgin)
                    {
                        screenDesgin.title = req.values.title;
                        screenDesgin.image_url = req.values.image_url;
                        screenDesgin.content = req.values.content;
                        screenDesgin.update_date = System.DateTime.Now.ToString();
                        _db.Updateable(screenDesgin).ExecuteCommand();
                    }
                    res.result = new Result() { data = true };
                }
            }
            catch (Exception ex)
            {
                Logger.Warn($"暂存，保存画布出现异常!{ex}");
                res.result = new Result() { data = false };
            }
            return res;
        }

        /// <summary>
        /// 获取画布数据
        /// </summary>
        /// <param name="requeset"></param>
        /// <returns></returns>
        public Response read(readReq req)
        {
            Response res = new Response();
            var pannel = new PannelResult();

            try
            {
                if (req.ids.Count > 0)
                {
                    var listScreenDesgin = _db.Queryable<ScreenDesginRecord>().In(a => a.id, req.ids).ToList();
                    List<DataItem> listDataItem = new List<DataItem>();
                    foreach (var screenDesgin in listScreenDesgin)
                    {
                        DataItem dataItem = new DataItem();
                        dataItem.id = screenDesgin.id;
                        dataItem.title = screenDesgin.title;
                        dataItem.content = screenDesgin.content;
                        dataItem.image_url = JsonConvert.DeserializeObject<List<Image_urlItem>>(screenDesgin.image_url);
                        listDataItem.Add(dataItem);
                    }
                    pannel.data = listDataItem;
                    res.result = new Result { data = pannel.data };
                }
            }
            catch (Exception ex)
            {
                Logger.Warn($"获取画布数据出现异常!{ex}");
                res.result = null;
            }
            return res;
        }

        /// <summary>
        /// 创建画布
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response create(createReq req)
        {
            Response res = new Response();
            try
            {
                if (req != null)
                {
                    ScreenDesginRecord screenDesgin = new ScreenDesginRecord();
                    var data = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(req.image_url);
                    screenDesgin.id = data[0]["name"].ToString();
                    screenDesgin.title = req.title;
                    screenDesgin.content = req.content;
                    screenDesgin.image_url = req.image_url;
                    screenDesgin.update_date = System.DateTime.Now.ToString();
                    _db.Insertable(screenDesgin).ExecuteCommand();
                    res.result = new Result { data = screenDesgin.id };
                }
            }
            catch (Exception ex)
            {
                Logger.Warn($"创建画布出现异常!{ex}");
                res.result = null;
            }
            return res;
        }

        #endregion 接口方法
    }

    #region 接口入参

    /// <summary>
    /// 获取所有模板列表
    /// </summary>
    public class searchReq
    {
        /// <summary>
        /// //页码，0为第一页
        /// </summary>
        public int offset { get; set; }

        /// <summary>
        /// 每页数据量
        /// </summary>
        public int limit { get; set; }

        public List<string> fields { get; set; }
    }

    /// <summary>
    /// 删除模板
    /// </summary>
    public class deleteReq
    {
        public List<string> ids { get; set; }
    }

    /// <summary>
    /// 发布/取消发布模板入参
    /// </summary>
    public class onlineofflineReq
    {
        public List<string> ids { get; set; }
        public string state { get; set; }
    }

    /// <summary>
    /// 暂存，保存画布入参
    /// </summary>
    public class updateReq
    {
        public List<string> ids { get; set; }
        public values values { get; set; }
    }

    /// <summary>
    /// 获取画布数据入参
    /// </summary>
    public class readReq
    {
        public List<string> ids { get; set; }
        public List<string> fields { get; set; }
    }

    /// <summary>
    /// 创建画布入参
    /// </summary>
    public class createReq
    {
        public string title { get; set; }

        public string image_url { get; set; }

        public string content { get; set; }
    }

    #endregion 接口入参

    public interface MomApi : IBasicObject
    {
    }
}